//
//  PkManager.m
//  CardWarrior
//
//  Created by Tekka Xie on 12-4-27.
//  Copyright (c) 2012年 Tencent. All rights reserved.
//

#import "PkManager.h"
#import "GameDataManager.h"

@interface PkManager()
{
    // yes for valid, no for invalid, 1~52
    BOOL cardStatus[53]; 
    //NSInteger leftCardCount;
}

- (NSInteger)getRandom;
- (NSInteger)nextCardIndex:(NSInteger) index;
- (NSInteger)preCardIndex:(NSInteger) index;

- (BOOL)checkValid:(NSInteger)src with:(NSInteger)dst;

@end

@implementation PkManager

@synthesize hostCardCount;
@synthesize guestCardCount;

static PkManager* pInstance = nil;

+ (PkManager*)sharedInstance
{
    if (pInstance == nil)
    {
        pInstance = [[PkManager alloc] init];
        srand(time(0));
    }
    
    return pInstance;
}

- (id)init
{
    if (self = [super init])
    {
        [self clearPkData];
    }
    
    return self;
}

#pragma mark - interface method

- (NSInteger)drawCard:(BOOL)isHost
{
    if (isHost && hostCardCount == 0)
        return 0;
    
    if (!isHost && guestCardCount == 0)
        return 0;
    
    if (isHost)
        hostCardCount--;
    else
        guestCardCount--;
    
    //leftCardCount--;
    
    //NSLog(@"leftCardCount: %d, hostCardCount: %d, guestCardCount = %d", leftCardCount, hostCardCount, guestCardCount);
    
    NSInteger i = [self getRandom] % 52+1;
    
    while (1)
    {
        if (cardStatus[i] == YES)
        {
            cardStatus[i] = NO;
            return i-1;
        }
        
        i = [self nextCardIndex:i];
    }
}

- (BOOL)checkCardWhetherMarch:(UIImageView*)src withView:(UIImageView*)dst
{        
    NSNumber* srcNumber = [src.layer valueForKey:@"CardNumber"];
    NSNumber* dstNumber = [dst.layer valueForKey:@"CardNumber"];
    
    return [self checkValid:[srcNumber integerValue] with:[dstNumber integerValue]];
}

#pragma mark - private
            
- (NSInteger)getRandom
{
    return rand();
}

- (NSInteger)nextCardIndex:(NSInteger)index
{
    index++;
    
    if (index == 53)
        index = 1;
    
    return index;
}

- (NSInteger)preCardIndex:(NSInteger)index
{
    index--;
    
    if (index == 0)
        index = 52;
    
    return index;
}

- (BOOL)checkValid:(NSInteger)src with:(NSInteger)dst
{
    if (abs(src-dst) == 1)
        return YES;
    
    if (src == 1 && dst == 13)
        return YES;
    
    if (src == 13 && dst ==1)
        return YES;
    
    return NO;
}

- (void)clearPkData
{
    for (int i = 0; i < 53; i++)
        cardStatus[i] = YES;
    
    //leftCardCount = 52;
    hostCardCount = 26;
    guestCardCount = 26;
}

@end
